<template>
    <div>
      <div>
        <p class="fwbold fs-md mg20">· 服务券配额申请</p>
        <el-divider></el-divider>
      </div>
      <div class="CouponApply">
        <div v-if="dataList.length > 0" class="w100 pb10">
          <div v-for="(item, index) in dataList" :key="index" :class="['coupon-item','mb20','pb10', item.voucherTypeId === '1717575751449443' ? 'top-block' : 'top-block1']">
            <div class="coupon-box w100 boxSizing pd10">
              <!-- <div class="year">2024</div> -->
              <div class="row-spaceb boxSizing">
                <div class="fwbold fs16">{{ item.voucherTypeName }}
                  <span v-if="[1, 3].includes(item.applyStatus)" class="color-grey fs14 ml30">券号：{{ item.voucherId }}</span>
                  <span class="ml30 color-grey">{{userInfo.companyTypeName}}</span>
                </div>
                <div class="fs-sm color-grey" v-if="[-2, -1, 0, 2].includes(item.applyStatus)">配额有效期：<span
                    class="color-red">{{
                      item.validBeginTime | timeFilter }}~{{
                      item.validEndTime | timeFilter }}</span></div>
                <div class="fs-sm color-grey" v-else-if="[1, 3].includes(item.applyStatus)">额度有效期：<span class="color-red">{{
                  item.validBeginTime | timeFilter }}~{{
                      item.validEndTime | timeFilter }}</span></div>
              </div>
              <div class="row-start color-grey">
                <div class="fs-sm mt10" style="line-height: 2;">
                  <div v-if="[1, 3].includes(item.applyStatus)" class="row-start-col-end wrap">
                    <div>优惠总额度：<span class="color-red fs18 mr5 fwbold">{{ item.totalSum | moneyFilter(item.applyStatus) }}</span>元券</div>
                    <div class="ml30">已使用优惠额度：<span class="fs16 color-red">{{ item.useSum | moneyFilter(item.applyStatus) }}</span>元</div>
                    <div class="ml30">剩余优惠额度：<span class="fs16 color-red fwbold">{{ item.balanceSum | moneyFilter(item.applyStatus) }}元</span></div>
                  </div>
                  <div class="desc" v-html="item.voucherTypeDescribe"></div>
                </div>
              </div>
              <div v-if="item.applyStatus === 3" class="mt10 fs14">
                审核未通过原因：
                <span class="color-grey mr20">{{ item.remark }}</span>
              </div>
            </div>
            <div class="btn tc mt10">
              <el-button v-if="item.applyStatus === -2" disabled type="primary" size="medium"
                @click="tipVisible = true">暂不可配额</el-button>
              <el-button v-if="item.applyStatus === -1" type="primary" size="medium"
                @click="openDialog(item)">服务券配额申请</el-button>
              <div v-if="item.applyStatus === 0 || item.applyStatus === 6" class="status-tag blue">待审核</div>
              <el-button v-if="item.applyStatus === 1" type="primary" size="medium" @click="goToIndex">去使用</el-button>
              <div v-if="item.applyStatus === 2" class="status-tag">审核未通过</div>
              <el-button v-if="item.applyStatus === 3" type="danger" size="medium"
                @click="openDialog(item)">退回修改</el-button>
              <div v-if="item.applyStatus === 4" class="status-tag">不可用</div>
            </div>
          </div>
          <el-pagination v-if="total > pageParams.pageNum" class="pagination" background @current-change="getVoucherList"
            :current-page.sync="pageParams.pageNo" :page-size="pageParams.pageNum" layout="prev, pager, next"
            :total="total">
          </el-pagination>
        </div>
        <el-empty v-else :image-size="50" description="您所属的企业不满足申请条件，如不是制造业企业，暂无优惠券可申领" />

        <el-dialog title="服务券配额" :visible.sync="dialogVisible" width="788px" custom-class="my-dialog">
          <el-table :data="tableList" border :span-method="objectSpanMethod" style="margin-top: -10px;">
            <el-table-column label="企业类型" prop="companyTypeName" min-width="50"></el-table-column>
            <el-table-column label="补贴金额(每年）" prop="quotaAmount" min-width="25">
              <template #default="scope">
                <div class="tc">{{ scope.row.quotaAmount }}万</div>
              </template>
            </el-table-column>
            <el-table-column label="服务券类型" prop="voucherTypeName" min-width="25">
            </el-table-column>
          </el-table>
          <div class="row-center mt20">系统将根据<span class="color-red">企业划型</span>，自动申请对应额度服务券。请确认是否需要服务券配额申请？</div>
          <div class="row-center" slot="footer">
            <el-button @click="dialogVisible = false" type="info" size="medium">暂不需要</el-button>
            <el-button style="margin-left: 40px;" type="primary" size="medium" @click="applySubmit">确定配额申请</el-button>
          </div>
        </el-dialog>
        <!-- <el-dialog title="服务券配额" :visible.sync="quotaDialogVisible" width="800px" custom-class="my-dialog">
          <div class="quota-table">
            <el-table :data="quotaTableData" border>
              <el-table-column label="服务类型" prop="serviceType" align="center"></el-table-column>
              <el-table-column label="专项服务券额度" prop="quotaLimit" align="center"></el-table-column>
            </el-table>
          </div>
          <div class="quota-form mt20">
            <p class="tip-text text-center">请需要申领的企业<span class="color-red">按需</span>填写申领额度，具有可获得的额度待有关部门审核后确定。</p>
            <div class="form-item mt20">
              <div class="label-box">
                <span class="required">*</span>
                <span><span class="color-red">融资担保</span>专项券申领额度：</span>
              </div>
              <el-input 
                v-model="quotaForm.financing" 
                placeholder="请输入申领额度 (0~100万)"
                class="quota-input">
                <template #append>万</template>
              </el-input>
            </div>
            <div class="form-item mt20">
              <div class="label-box">
                <span class="required">*</span>
                <span><span class="color-red">直接设备租赁</span>专项券申领额度：</span>
              </div>
              <el-input 
                v-model="quotaForm.equipment" 
                placeholder="请输入申领额度 (0~50万)"
                class="quota-input">
                <template #append>万</template>
              </el-input>
            </div>
          </div>

          <div slot="footer" class="dialog-footer">
            <el-button @click="quotaDialogVisible = false" type="info">暂不需要</el-button>
            <el-button type="primary" @click="submitQuota">确定申领</el-button>
          </div>
        </el-dialog> -->
        <el-dialog :title="currentCoupon?.voucherTypeName || '服务券配额'" :visible.sync="quotaDialogVisible" width="800px" custom-class="my-dialog">
          <div class="quota-table" v-if="currentCoupon">
            <el-table :data="[{
              serviceType: currentCoupon.voucherTypeName,
              quotaLimit: currentCoupon.voucherTypeDescribe
            }]" border>
              <el-table-column label="服务类型" prop="serviceType" align="center" width="200"></el-table-column>
              <el-table-column label="专项服务券额度说明" align="center">
                <template #default="scope">
                  <div class="desc-content" v-html="scope.row.quotaLimit"></div>
                </template>
              </el-table-column>
            </el-table>
          </div>
          
          <div class="quota-form mt20">
            <p class="tip-text text-center">请需要申领的企业<span class="color-red">按需</span>填写申领额度，具有可获得的额度待有关部门审核后确定。</p>
            <div class="form-item mt20">
              <div class="label-box">
                <span class="required">*</span>
                <span><span class="color-red">{{ currentCoupon?.voucherTypeName }}</span>申领额度：</span>
              </div>
              <el-input 
                v-model="quotaForm.amount" 
                :placeholder="getPlaceholder(currentCoupon?.voucherTypeName)"
                class="quota-input">
                <template #append>万</template>
              </el-input>
            </div>
            <div class="form-item mt20">
              <div class="label-box">
                <span>上传合同凭证：</span>
              </div>
              <div class="row-start ml10">
                  <div v-if="quotaForm.contractFileId" class="mb15">{{quotaForm.contractFileName}} <i v-if="quotaForm.contractFileName" class="el-icon-circle-check color-primary mr5"></i></div>
                  <upload-file  @setFileUrl="upLoadFile($event)"></upload-file>
                </div>
            </div>
          </div>

          <div slot="footer" class="tc">
            <el-button @click="quotaDialogVisible = false" type="info">暂不需要</el-button>
            <el-button type="primary" @click="submitQuota">确定申领</el-button>
          </div>
        </el-dialog>
          <!-- 需要认证提示 -->
          <el-dialog title="服务券配额" :visible.sync="tipVisible" width="525px" custom-class="my-dialog">
            <p style="margin-top: -10px;">需要完成<span
                style="color: #436AF7;">"企业信息认证"</span>才可进行"服务券配额申请"、"申请入驻"或"支付认证"的操作，请先完成认证。</p>
            <div style="text-align: right;margin-top: 40px;">
              <el-button type="info" size="medium" @click="tipVisible = false">暂不认证</el-button>
              <el-button type="primary" size="medium" class="blue-btn"
                @click="() => { tipVisible = false; goToAuth() }">前往认证</el-button>
            </div>
          </el-dialog>
      </div>
    </div>
</template>
<script>
import { voucherPage, voucherApply,getVoucherCompanyType } from '@/api/homeApi'
import moment from 'moment';
import { mapGetters } from 'vuex'
import uploadFile from "@/components/upload/uploadFile";
export default {
  filters: {
    timeFilter: function (value) {
      return moment(value).format('yyyy年MM月DD日');
    },
    moneyFilter: function (value, applyStatus) {
      if (applyStatus === 3) return '--'
      let res = ''
      if (isNaN(value)) {
        res = '-'
      } else {
        res = value / 100
      }
      return res
    }
  },
  data() {
    return {
      dataList: [
        {voucherTypeName: '2025年服务券',voucherId: '',applyStatus: -2,validBeginTime: 1622505600000,validEndTime: 1625097600000,voucherTypeDescribe: ''}
      ],
      pageParams: {
        pageNo: 1,
        pageNum: 4
      },
      total: 0,
      dialogVisible: false,
      tableList: [],
      currentCoupon: null,
      tipVisible: false,
      refreshTimer: null, // 用于存储定时器ID
      quotaDialogVisible: false,
      quotaTableData: [
        {
          serviceType: '融资担保',
          quotaLimit: '每家企业每年可使用服务券额度最高不超100万元，支持期限不超过3年'
        },
        {
          serviceType: '直接设备租赁',
          quotaLimit: '每家企业每年最高可使用服务券额度不超过50万元，支持期限不超过3年'
        }
      ],
      quotaForm: {
        amount: '',
        contractFileId: '',
        contractFileName: ''
      },
    }
  },
  created() {
    const data = [
      { companyTypeName: '专精特新"小巨人"企业', quotaAmount: 30, voucherTypeName: '通用券' }
    ]
  },
  beforeDestroy() {
    // 离开页面时清除定时器
    if (this.refreshTimer) {
      clearInterval(this.refreshTimer);
    }
  },
  computed: {
    ...mapGetters(['userInfo'])
  },
  components: {
    uploadFile
  },
  mounted() {
    this.getVoucherList();
    this.VoucherCompanyType();
  },
  methods: {
    upLoadFile({ fileId, fileName }) {
        this.quotaForm.contractFileId = fileId
        this.quotaForm.contractFileName = fileName
    },
    openDialog(val) {
          // 提示当前暂时不开放服务券申请
          /*
          this.$confirm('当前暂时不开放服务券申请', '提示', {
            confirmButtonText: '确定',
            type: 'warning',
            showCancelButton: false,
            closeOnClickModal: false,
            closeOnPressEscape: false
          });
          return
          */
          // 后期需要把通用券改成专项券
          if (val.voucherTypeName.includes('专项券')) {
            this.quotaDialogVisible = true
          } else {
            this.dialogVisible = true
          }
          this.currentCoupon = val
          this.quotaForm.amount = ''
        },
    getPlaceholder(type) {
        if (!type) return '请输入申领额度'
        if (type.includes('融资担保')) {
          return '请输入申领额度 (0~100万)'
        } else if (type.includes('设备租赁')) {
          return '请输入申领额度 (0~50万)'
        }
        return '请输入申领额度'
    },
    submitQuota() {
      if (!this.quotaForm.amount) {
        this.$message.warning('请填写申领额度')
        return
      }
      
      const amount = Number(this.quotaForm.amount)
      let maxAmount = 50 // 默认最大额度
      
      if (this.currentCoupon?.voucherTypeName.includes('融资担保')) {
        maxAmount = 100
      }
      
      if (isNaN(amount) || amount < 0 || amount > maxAmount) {
        this.$message.warning(`申领额度需在0-${maxAmount}万之间`)
        return
      }

      voucherApply({
        voucherTypeId: this.currentCoupon.voucherTypeId,
        applyQuota: amount,
        contractFileId: this.quotaForm.contractFileId,
        voucherId: this.currentCoupon.voucherId
      }).then(res => {
        if (res.code === 200) {
          this.$message.success('配额申请成功')
          this.quotaDialogVisible = false
          this.getVoucherList()
        }
      })
    },
    VoucherCompanyType(){
      getVoucherCompanyType().then(res => {
        if (res.code === 200) {
          this.tableList = res.data
          this.tableList.forEach((item, index, arr) => {
            item.rowspan = [1, 1, 1]
            const match1 = arr.findIndex(i => i.voucherTypeName === item.voucherTypeName)
            const len1 = arr.filter(i => i.voucherTypeName === item.voucherTypeName).length
            item.rowspan[2] = match1 === index ? len1 : 0
            const match2 = arr.findIndex(i => i.voucherTypeName === item.voucherTypeName && i.quotaAmount === item.quotaAmount)
            const len2 = arr.filter(i => i.voucherTypeName === item.voucherTypeName && i.quotaAmount === item.quotaAmount).length
            item.rowspan[1] = match2 === index ? len2 : 0
          })
        }
      })
    },
    goToAuth(){
      this.$router.push({ name: '个人中心' })
    },
    getVoucherList() {
      voucherPage(this.pageParams).then(res => {
        if (res.code === 200) {
          // 先过滤出applyStatus >= 0的元素
          // const filteredData = res.rows.filter(item => item.applyStatus >= 0);
          // 如果过滤后的数组为空，则使用原数组；否则使用过滤后的数组
          this.dataList = res.rows;
          this.total = res.total;
        } else {
          this.total = 0
        }
      })
    },
    goToIndex() {
      this.$router.push({
        name: '首页'
      })
    },
    applySubmit() {
      voucherApply({
        voucherTypeId: this.currentCoupon.voucherTypeId
      }).then(res => {
        if (res.code === 200) {
          this.$message({
            type: 'success',
            message: '配额成功'
          })
          this.getVoucherList();
        // 设置定时器，每隔10秒刷新页面
          this.refreshTimer = setInterval(() => {
            this.getVoucherList();
          }, 10000);
        } else {
          this.$message({
            type: 'warning',
            message: '配额失败'
          })
        }
        this.dialogVisible = false
      })
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      return {
        rowspan: row.rowspan[columnIndex],
        colspan: 1,
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import "@/assets/css/element-variables";

:deep(.el-table .el-table__cell) {
  padding: 6px 0;
}

:deep(.el-table th.el-table__cell) {
  background: #f5f7fa;
}
.top-block {
  background: url('~@/assets/image/coupon_bg2.png') no-repeat;
  background-size: 100% 100%;
}
.top-block1 {
  background: url('~@/assets/image/coupon_bg3.png') no-repeat;
  background-size: 100% 100%;
}
.CouponApply {
  padding: 0 10px;
  height: 100%;
  overflow: auto;
}

.coupon-item {
  &+.coupon-item {
    margin-top: 0px;
  }
}

.coupon-box {
  position: relative;
  padding: 17px 37px 0px 11%;
  overflow: hidden;
  min-height: 80px;

  .year {
    position: absolute;
    top: 0px;
    left: 0;
    font-size: 32px;
    color: #fff;
    font-family: 'MicrosoftYaHei';
    letter-spacing: 1px;
    width: 8%;
    text-align: center;
  }

  .pre-dot {
    position: relative;
    padding-left: 15px;

    &::before {
      content: '';
      position: absolute;
      top: 8px;
      left: 0;
      display: block;
      width: 5px;
      height: 5px;
      border-radius: 50%;
      background-color: $text-color-red;
    }
  }

  ::v-deep .desc {
    p {
      position: relative;
      margin: 0;
      padding-left: 15px;

      &::before {
        content: '';
        position: absolute;
        top: 12px;
        left: 0;
        display: block;
        width: 5px;
        height: 5px;
        border-radius: 10px;
        background-color: $text-color-red;
      }
    }
  }
  .btn {
    position: absolute;
    right: 36px;
    bottom: 20px;

    .status-tag {
      display: inline-block;
      min-width: 142px;
      border-radius: 3px;
      font-size: 14px;
      padding: 8px 20px;
      background-color: #CFCFCF;
      color: #fff;
      text-align: center;
      box-sizing: border-box;

      &.blue {
        background-color: rgba(67, 106, 247, 0.1);
        color: $--color-primary;
      }
    }

    .el-button {
      min-width: 142px;
      border-radius: 3px;
      font-size: 14px;
      padding: 8px 20px;
    }

    .el-button--info {
      background-color: #CFCFCF;
      border-color: #CFCFCF;
      color: $text-color;
    }
  }
}

  .btn {
    right: 36px;
    bottom: 20px;

    .status-tag {
      display: inline-block;
      min-width: 142px;
      border-radius: 3px;
      font-size: 14px;
      padding: 8px 20px;
      background-color: #CFCFCF;
      color: #fff;
      text-align: center;
      box-sizing: border-box;

      &.blue {
        background-color: rgba(67, 106, 247, 0.1);
        color: $--color-primary;
      }
    }

    .el-button {
      min-width: 142px;
      border-radius: 3px;
      font-size: 14px;
      padding: 8px 20px;
    }

    .el-button--info {
      background-color: #CFCFCF;
      border-color: #CFCFCF;
      color: $text-color;
    }
  }

.pagination {
  margin-top: 20px;
  text-align: right;
}
.quota-table {
  margin-bottom: 20px;
  
  :deep(.el-table) {
    margin-top: -10px;
    
    .el-table__header th {
      background-color: #f5f7fa;
      color: #606266;
    }
    
    .desc-content {
      text-align: left;
      padding: 5px 10px;
      
      :deep(p) {
        margin: 0;
        line-height: 1.6;
      }
    }
  }
}

.quota-form {
  width: 700px;
  margin: 0 auto;
  
  .tip-text {
    text-align: center;
    color: #666;
    font-size: 14px;
  }
  
  .form-item {
    display: flex;
    align-items: center;
    justify-content: row-start;
    
    .label-box {
      width: 240px;
      text-align: right;
      
      .required {
        color: #F56C6C;
        margin-right: 4px;
      }
    }
    
    .quota-input {
      width: 300px;
      margin-left: 10px;
    }
  }
}

.color-red {
  color: #F56C6C;
}
</style>